package com.ds.infrastructure.audit.collector.config;

import com.ds.infrastructure.audit.collector.handler.SsoAuthenticationFailureHandler;
import com.ds.infrastructure.audit.collector.handler.SsoAuthenticationSuccessHandler;
import com.ds.infrastructure.audit.collector.interceptor.AuthRequestFilter;
import com.ds.infrastructure.audit.collector.security.SSOAuthenticationProvider;
import com.ds.infrastructure.audit.collector.security.SsoAuthenticationFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.annotation.Resource;
import java.util.Collections;

/**
 * 作用：
 *
 * @author WeiShaoying
 * @date 2020/8/10
 */
@ConditionalOnProperty("sso.enable")
@EnableGlobalMethodSecurity(jsr250Enabled = true, prePostEnabled = true, securedEnabled = true)
@Slf4j
@SuppressWarnings("all")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Resource
    private SSOAuthenticationProvider authenticationProvider;

    @Resource
    private SSOConfig ssoConfig;

    @Autowired
    private SsoAuthenticationSuccessHandler successHandler;

    @Autowired
    private SsoAuthenticationFailureHandler failureHandler;

    @Autowired
    private AuthRequestFilter authRequestFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        log.info("Spring Security 已启用");
        http.addFilterBefore(new SsoAuthenticationFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(authRequestFilter, UsernamePasswordAuthenticationFilter.class)
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                //.authorizeRequests().antMatchers("/app/**").permitAll().anyRequest().authenticated().and()
                .cors()
                .and().exceptionHandling()
                .and()
                .csrf().disable()
        ;
        http.formLogin().successHandler(successHandler).failureHandler(failureHandler);
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider);
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(ssoConfig.getAllowedOrigins());
        configuration.setAllowedMethods(Collections.singletonList("*"));
        configuration.addAllowedHeader("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
